import { Component } from "@angular/core";
import {
  IonicPage,
  NavController,
  NavParams,
  ToastController,
  App,
  Events,
  AlertController
} from "ionic-angular";
import { TeamSeriveProvider } from "../../../../providers/team-serive/team-serive";
import { PcSeriveProvider } from "../../../../providers/pc-serive/pc-serive";
import { BaseUI } from "../../../../common/baseUI";
import { concat } from "rxjs/observable/concat";
import {
  trigger,  state,  style, animate, transition, keyframes, animateChild
} from '@angular/animations';
/**
 * Generated class for the TeamDetailsPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage() 
@Component({
  selector: "page-team-details",
  templateUrl: "team-details.html",
  animations: [
    trigger('toggle', [
      transition('void => *', [
        style({}),
        animate(1000, keyframes([
          style({}), // offset = 0
          style({}), // offset = 0.33
          style({}), // offset = 0.66
          style({}) // offset = 1
        ])) 
      ])
    ])
  ]
})

export class TeamDetailsPage extends BaseUI {
  //团队名称
  teamName: string;
  //团队人数
  teamNumber: string;
  //团队头像
  teamPhoto: string;
  //团队编号
  teamcode: number;
  //使用者编号
  usercode: number;
  //团队成员
  teamMemberDatas: Array<any> = [];
  //评测列表
  evaluating: Array<any> = [];
  bgUrl: string;  
  //是否有权限创建评测
  canCreateEvaluating;
  //是否加入了当前团队 默认false
  isJoinTeam: Boolean = false;
  //是否展示删除按钮
  showDeteleBtn: boolean;
  //是否是管理员
  IsAdministrators: boolean;

  constructor( 
    public navCtrl: NavController,
    public navParams: NavParams,
    public teamSeriveProvider: TeamSeriveProvider,
    public toastCtrl: ToastController,
    public app: App,
    public pcSeriveProvider: PcSeriveProvider, 
    public events: Events,
    public alertCtrl: AlertController
  ) {
    super();
    this.teamcode = this.navParams.get("teamcode");
    let teamimg = JSON.parse(localStorage.getItem('teamimg'));
     
    for (let index = 0; index < teamimg.length; index++) {
      if(this.teamcode == teamimg[index]['teamcode']){
        console.log(teamimg[index]['teambg']);
        this.bgUrl = this.pcSeriveProvider.imgdate[teamimg[index]['teambg']].img;
      }
    }
    // this.bgUrl = this.pcSeriveProvider.imgdate[this.pcSeriveProvider.rand()].img;
  }

  ionViewWillEnter() {
    //初始化
    this.init();
    //是否加入了该团队
    this.teamSeriveProvider.getIsJoinTeam(this.teamcode).subscribe(
      data => {
        if (data["status"] == 400 && data["msg"] == "没有加入该团队") {
          this.isJoinTeam = false;
          return;
        }
        if (data["status"] == 500) {
          this.loginTimeOut();
          return;
        }
        this.isJoinTeam = true;
      },
      err => {
        super.showToast(this.toastCtrl, "请求数据失败，请重试");
      }
    );
  }

  init() {
    //请求团队信息
    this.teamSeriveProvider.getTeamDetails(this.teamcode).subscribe(
      data => {
        if (data != null) {
          if (data.status != 500) {
            this.teamName = data.team.teamname;
            this.teamNumber = data.team.teamcount + "人";
            this.teamPhoto = data.team.teamicon;
            this.teamMemberDatas = data.user;
            this.evaluating = data.evaluating ? data.evaluating : [];
          } else {
            this.loginTimeOut();
          }
        }
      },
      err => {
        super.showToast(this.toastCtrl, "请求数据失败，请重试");
      }
    );
  }

  /**
   * 点击团队成员头像
   * @param item 点击项的数值
   */
  openMemberDetails(item) {
    this.navCtrl.push("MemberDetailsPage", {
      item
    });
  }

  //创建评测
  openNewApply() {
    if (this.canCreateEvaluating == null) {
      this.teamSeriveProvider.getCanCreateEvaluating(this.teamcode).subscribe(
        data => {
          if (data["status"] == 200) {
            this.canCreateEvaluating = true;
            this.navCtrl.push("PcCreaterEvaluatingPage", {
              teamcode: this.teamcode
            });
          } else if (data["status"] == 500) {
            this.loginTimeOut();
          } else {
            this.canCreateEvaluating = false;
            super.showToast(this.toastCtrl, "没有权限创建评测");
          }
        },
        err => {
          super.showToast(this.toastCtrl, "请求数据失败，请重试");
        }
      );
      return;
    }
    if (this.canCreateEvaluating) {
      this.navCtrl.push("PcCreaterEvaluatingPage", {
        teamcode: this.teamcode
      });
    } else {
      super.showToast(this.toastCtrl, "没有权限创建评测");
    }
  }

  //加入团队
  join() {
    //如果
    if (!this.isJoinTeam) {
      this.teamSeriveProvider.joinTeam(this.teamcode).subscribe(
        data => {
          if (data != null) {
            if (data.status != 500) {
              if (data.status == 400) {
                super.showToast(this.toastCtrl, "你已经在该团队了");
                return;
              }
              this.showToast(this.toastCtrl, "加入团队成功");
              this.isJoinTeam = true;
              this.events.publish("team:created"); //发布团队创建事件
              this.init();
              //当前不需要审核
              // this.navCtrl.push("TeamApplyPage");
            } else {
              this.loginTimeOut();
            }
          }
        },
        err => {
          super.showToast(this.toastCtrl, "请求数据失败，请重试");
        }
      );
    } else {
      this.exitTeam(this.teamcode);
    }
  }

  //退出团队
  exitTeam(teamcode) {
    this.teamSeriveProvider.getCanCreateEvaluating(this.teamcode).subscribe(
      data => {
        if (data["status"] == 200) {
          this.showToast(this.toastCtrl, "创建者目前无法退出团队");
        } else if (data["status"] == 500) {
          this.loginTimeOut();
        } else {
          this.teamSeriveProvider.exitTeam(teamcode).subscribe(
            data => {
              if (data["status"] == 200 && data["msg"] == "OK") {
                this.showToast(this.toastCtrl, "退出团队成功");
                this.isJoinTeam = false;
                this.init();
                return;
              }
              if (data["status"] == 500) {
                this.loginTimeOut();
                return;
              }
              this.showToast(this.toastCtrl, "退出团队失败");
            },
            err => {
              super.showToast(this.toastCtrl, "请求数据失败，请重试");
            }
          );
        }
      },
      err => {
        super.showToast(this.toastCtrl, "请求数据失败，请重试");
      }
    );
  }

  //跳转到评测界面
  openPcSmItemPage(item) {
    if (this.isJoinTeam == null) {
      //第一次从服务器获取是否加入了该团队
      this.teamSeriveProvider.getIsJoinTeam(this.teamcode).subscribe(
        data => {
          if (data["status"] == 200 && data["msg"] == "OK") {
            this.isJoinTeam = true;
          } else {
            this.isJoinTeam = false;
          }
          this.isJoin(item);
        },
        err => {
          super.showToast(this.toastCtrl, "请求数据失败，请重试");
        }
      );
    } else {
      this.isJoin(item);
    }
  }

  //是否加入了团队
  isJoin(item) {
    //如果为真 代表加入了团队 不用二次请求
    if (this.isJoinTeam) {
      this.timestate(item);
      return;
    }
    if (this.isJoinTeam === false) {
      super.showToast(this.toastCtrl, "只有加入团队的成员才能参加评测");
      return;
    }
  }

  //判断时间状态是否开启评测
  timestate(item) {
    let tday = new Date();
    let rday = new Date(item["evaluatingtime"]);
    let eday = new Date(item["evaluatingendtime"]);
    rday.setHours(0, 0, 0);
    eday.setHours(23, 59, 59);
    if (rday.valueOf() <= tday.valueOf() && tday.valueOf() <= eday.valueOf()) {
      //开启
      this.navCtrl.push("PcSmItemPage", {
        teamImg: this.teamPhoto,
        evaluatingCode: item.evaluatingcode
      });
    } else if (
      rday.valueOf() > tday.valueOf() &&
      tday.valueOf() <= eday.valueOf()
    ) {
      super.showToast(this.toastCtrl, "该评测目前还没开始"); //未开始
    } else {
      super.showToast(this.toastCtrl, "该评测已经结束"); //结束
      this.navCtrl.push("PcReportPage", {
        teamCode: this.teamcode,
        evalcode: item.evaluatingcode
      });
    }
  } 

  //长按事件
  doPress(){
    if(this.IsAdministrators == null){
      this.teamSeriveProvider.getCanCreateEvaluating(this.teamcode).subscribe(
        data => {
          if (data["status"] == 200) {
            this.IsAdministrators = true;
            this.showDeteleBtn = true;
          } else if (data["status"] == 500) {
            this.loginTimeOut();
          } else {
            this.IsAdministrators = false;
            this.showToast(this.toastCtrl, "只有创建者能进行删除操作");
          }
        },
        err => {
          super.showToast(this.toastCtrl, "请求数据失败，请重试");
        }
      );
    }else if(!this.IsAdministrators){
      this.showToast(this.toastCtrl, "只有创建者能进行删除操作");
    }else{
      this.showDeteleBtn = true;
    }
  }

  //删除成员
  deleteMember(event, item){
    const confirm = this.alertCtrl.create({
      title: '',
      message: `确认要删除该成员${item.realname}吗?`,
      buttons: [
        {
          text: '取消',
          handler: () => {
          }
        },
        {
          text: '确认',
          handler: () => {
            this.removeMember(item.usercode);
          }
        }
      ]
    });
    confirm.present();
    event.stopPropagation();
  }

  //删除成员请求
  removeMember(usercode){
    this.teamSeriveProvider.removeMember(this.teamcode, usercode).subscribe(data => {
      if(data.status == 200){
        this.showToast(this.toastCtrl, "删除成员成功");
        this.init();
      } else if(data.status == 500) {
        this.loginTimeOut();
      } else if(data.status == 400){
        super.showToast(this.toastCtrl, "你不能踢掉你自己");
      } else {
        super.showToast(this.toastCtrl, "删除成员失败");
      }
    }, err => {
      super.showToast(this.toastCtrl, "请求数据失败，请重试");
    });
  }

  //登录超时
  loginTimeOut() {
    super.showToast(this.toastCtrl, "登录失效，请重新登录");
    this.app.getRootNav().setRoot("LoginOrRegisterPage");
  }

  //返回
  back() {
    this.navCtrl.pop();
  }
}
